#include "PlayerCharacter.h"
#include <QRandomGenerator>

using namespace MyNS;

PlayerCharacter::PlayerCharacter(MapManager *mapManager, QObject *parent)
    : Character(parent), m_mapManager(mapManager)
{
    // 设置玩家特有属性
    setSpeed(180.0f);

    //初始化玩家pokemon
    playerPokemon.append(playerPokemon101);
    playerPokemon.append(playerPokemon102);
    playerPokemon.append(playerPokemon103);
    playerPokemon.append(playerPokemon104);
    playerPokemon.append(playerPokemon105);
    playerPokemon.append(playerPokemon106);
}

void PlayerCharacter::update(float deltaTime)
{
    // 调用基类动画更新
    Character::update(deltaTime);

    // 1. 计算移动向量
    QPointF rawDirection(0, 0);
    if (m_moveUp)
        rawDirection.setY(rawDirection.y() - 1);
    if (m_moveDown)
        rawDirection.setY(rawDirection.y() + 1);
    if (m_moveLeft)
        rawDirection.setX(rawDirection.x() - 1);
    if (m_moveRight)
        rawDirection.setX(rawDirection.x() + 1);

    // 2. 如果有移动输入
    if (!rawDirection.isNull()) {
        // 归一化移动向量
        float length = std::sqrt(rawDirection.x() * rawDirection.x() +
                                 rawDirection.y() * rawDirection.y());

        QPointF normalizedDirection = rawDirection / length;

        // 根据是否冲刺选择速度
        float currentSpeed = m_isSprinting ? speed() * 1.5f : speed();
        QPointF movement = normalizedDirection * currentSpeed * deltaTime;

        // 应用移动（带碰撞检测）
        moveWithCollision(movement.x(), movement.y());

        // 设置方向
        if (std::abs(rawDirection.x()) > std::abs(rawDirection.y())) {
            setCurrentDirection(rawDirection.x() > 0 ? DIR_RIGHT : DIR_LEFT);
        } else {
            setCurrentDirection(rawDirection.y() > 0 ? DIR_DOWN : DIR_UP);
        }
    }

    // 3. 定期检查遭遇
    m_encounterTimer += deltaTime;
    if (m_encounterTimer >= ENCOUNTER_CHECK_INTERVAL) {
        m_encounterTimer = 0.0f;
        handleWildEncounter();
    }
}

void PlayerCharacter::moveWithCollision(float dx, float dy)
{
    QPointF newPos = pos() + QPointF(dx, dy);

    // 地形碰撞检测
    if (checkTerrainCollision(newPos)) {
        return;
    }

    setPos(newPos);
}

void PlayerCharacter::handleInput(bool moveUp, bool moveDown,
                                  bool moveLeft, bool moveRight,
                                  bool isSprinting)
{
    m_moveUp = moveUp;
    m_moveDown = moveDown;
    m_moveLeft = moveLeft;
    m_moveRight = moveRight;
    m_isSprinting = isSprinting;
}



bool PlayerCharacter::checkTerrainCollision(const QPointF& newPos) const
{
    if (!m_mapManager) return true;

    // 计算玩家所在的网格坐标
    const int tileSize = MapManager::tileSize;
    int tileX = static_cast<int>(newPos.x() + boundingRect().width()/2) / tileSize;
    int tileY = static_cast<int>(newPos.y() + boundingRect().height()/2) / tileSize;

    // 获取当前地图数据
    const MapData &map = m_mapManager->getCurrentMapData();

    // 检查边界
    if (tileX < 0 || tileX >= map.width || tileY < 0 || tileY >= map.height) {
        return true;
    }

    // 检查地形是否可通行
    int tileType = map.tileData[tileY][tileX];
    return (tileType == TerrainType::WALL || tileType == TerrainType::WATER);
}


void PlayerCharacter::handleWildEncounter()
{
    // 10% 的几率遇到野生宝可梦
    if (m_mapManager && m_mapManager->isInGrassArea(pos())) {
        if (QRandomGenerator::global()->bounded(100) < 30) {
            emit wildPokemonEncountered();
        }
    }
}

void PlayerCharacter::initializeCollisionShape()
{
    setCollisionShapeMode(
        QGraphicsPixmapItem::HeuristicMaskShape); // 启发式近似（动态采样）
}
